package org.dromara.common.redis.utils

import org.dromara.common.core.utils.SpringUtils.getBean
import org.springframework.cache.CacheManager

/**
 * 缓存操作工具类
 *
 * @author LikeYouDo
 * @date 2025/1/6 19:31
 */
@Suppress("UNCHECKED_CAST")
object CacheUtils {
    private val CACHE_MANAGER: CacheManager = getBean(CacheManager::class.java)

    /**
     * 获取缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     */
    @JvmStatic
    fun <T> get(cacheNames: String, key: Any): T? {
        val wrapper = CACHE_MANAGER.getCache(cacheNames)?.get(key)
        return if (wrapper != null) wrapper.get() as T? else null
    }

    /**
     * 保存缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     * @param value      缓存值
     */
    @JvmStatic
    fun put(cacheNames: String, key: Any?, value: Any?) {
        if (key != null) {
            CACHE_MANAGER.getCache(cacheNames)?.put(key, value)
        }
    }

    /**
     * 删除缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     */
    @JvmStatic
    fun evict(cacheNames: String, key: Any) {
        CACHE_MANAGER.getCache(cacheNames)?.evict(key)
    }

    /**
     * 清空缓存值
     *
     * @param cacheNames 缓存组名称
     */
    @JvmStatic
    fun clear(cacheNames: String) {
        CACHE_MANAGER.getCache(cacheNames)?.clear()
    }
}
